//
//  LXPageContentView.swift
//  zhibo
//
//  Created by Echo on 16/9/22.
//  Copyright © 2016年 Echo. All rights reserved.
//

import UIKit

protocol PageContentViewDelegate : class {
    func pageContentViewScrolled(contentView : LXPageContentView,progress : CGFloat , sourceIndex : Int , targetIndex : Int)
}

private let ContentCellId = "ContentCellId"
class LXPageContentView: UIView {
    
    // MARK:- 属性
    private var isForbiddenScrollDelegate : Bool = false
    private var startOffsetX : CGFloat = 0
    weak var delegate : PageContentViewDelegate?
    private var childVCs : [UIViewController]
    private weak var parentVC : UIViewController?
    private lazy var collectionView : UICollectionView = {[weak self] in
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .Horizontal
        
        
        let collectionV = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        collectionV.showsHorizontalScrollIndicator = false
        collectionV.pagingEnabled = true
        collectionV.bounces = false
        collectionV.scrollsToTop = false
        collectionV.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellId)
        collectionV.dataSource = self
        collectionV.delegate = self
        return collectionV
        
        
    }()

    init(frame : CGRect , childVCs : [UIViewController] , parentVC : UIViewController){
        
        self.childVCs = childVCs
        self.parentVC = parentVC
        
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LXPageContentView{
    private func setupUI() {
        for childVc in childVCs {
            // 添加子控制器
            parentVC?.addChildViewController(childVc)
        }
        
        addSubview(collectionView)
        collectionView.frame = bounds
        
    }
}

// MARK:- UICollectionView数据源
extension LXPageContentView : UICollectionViewDataSource {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVCs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ContentCellId, forIndexPath: indexPath)
        
        // 清除之前的view ,添加子控制器的view
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        let childVc = childVCs[indexPath.item]
        childVc.view.frame = cell.contentView.bounds
        //子控制器的view添加到cell的contentView中
        cell.contentView.addSubview(childVc.view)
        
        return cell
    }
}

// MARK:- UICollectionView代理
extension LXPageContentView : UICollectionViewDelegate{
    
    //即将开始拖动
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        
        isForbiddenScrollDelegate = false
        
        startOffsetX = scrollView.contentOffset.x
        
    }
    
    //已经开始滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        // 判断是否是点击事件,是就继续;不是就退出
        if isForbiddenScrollDelegate {return}
        
        //
        var progress : CGFloat = 0
        var sourceIndex : Int = 0
        var targetIndex : Int = 0
        
        // 判断左滑还是右滑
        let currentOffsetX = scrollView.contentOffset.x
        let scrollViewWidth = scrollView.bounds.width
        
        if currentOffsetX > startOffsetX { // 左滑
            //
            progress = currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth)
            
            sourceIndex = Int(currentOffsetX / scrollViewWidth)
            
            targetIndex = sourceIndex + 1
            if targetIndex >= childVCs.count {
                // 如果是最后一位
                targetIndex = childVCs.count - 1
            }
            
            // 如果完全滑过去
            if currentOffsetX - startOffsetX == scrollViewWidth {
                progress = 1
                targetIndex = sourceIndex
            }
        } else {
            progress = 1 - (currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth))
            
            targetIndex = Int(currentOffsetX / scrollViewWidth)
            
            sourceIndex = targetIndex + 1
            
            if sourceIndex >= childVCs.count  {
                sourceIndex = childVCs.count - 1
            }
        }
        
        // 将参数传给titleView
        delegate?.pageContentViewScrolled(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
        
    }
}

// MARK:- 外部调用的方法
extension LXPageContentView{
    func setCurrentIndex(currentIndex : Int){
        
        isForbiddenScrollDelegate = true
        
        let offsetX = CGFloat(currentIndex) * collectionView.frame.width
        collectionView.setContentOffset(CGPoint(x:offsetX , y:0), animated: false)
    }
}
